//
//  LauAccount.swift
//  SwiftProject
//
//  Created by Lausen on 2017/8/7.
//  Copyright © 2017年 id. All rights reserved.
//

import UIKit

private let accountFile: NSString = "account.json"

/// 用户账户模型
class LauAccount: NSObject {

    /// 令牌
    var access_token: NSString?
    
    /// uid
    var uid: String?
    
    /// 用户的头像
    var avatar_large: String?
    
    /// 用户姓名
    var screen_name: String?
    
    /// 过期时间
    var expires_in: TimeInterval = 0{
        
        didSet{
            expiresDate = Date(timeIntervalSinceNow: expires_in)
        }
    }
    
    //过期日期
    var expiresDate: Date?
    
    
    override init() {
        super.init()
        
        //1:从沙盒加载账户文件,
        guard let filePath = accountFile.cz_appendDocumentDir(),//加载文件路径
            let data = NSData(contentsOfFile: filePath), //根据路径,获取到二进制文件
        let json = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [String: Any]//反序列化一下
        
            else{
                
            return
        }
        
        //2:设置当前账户
        self.yy_modelSet(withJSON: json ?? [:])
        
        //3:token过期的处理
//        expiresDate = Date(timeIntervalSinceNow: -60 * 60 * 24)
//        print("过期时间\(String(describing: expiresDate))")
        
        if ((expiresDate?.compare(Date())) == .orderedAscending) {
            
            print("当前的token过期了")
            //1:清空token和uid
            access_token = nil
            uid = nil
            
            //2:清空沙盒的账户文件
            try? FileManager.default.removeItem(atPath: filePath)
        }
    }
    
    override var description: String{
    
        return yy_modelDescription()
    }
    
    //MARK: -- 保存账户
    func saveAccount() {
        
        //1:先把账户转换成字典
        var dict = self.yy_modelToJSONObject() as? [String: Any] ?? [:]
        
        //2:删除expires_in
        dict.removeValue(forKey: "expires_in")
        
        //3:转换成二进制
        guard let data = try? JSONSerialization.data(withJSONObject: dict, options: []),
            //4:拼接路径
            let filePath = accountFile.cz_appendDocumentDir()
        else{
            
            return
        }
        
        //5:写入磁盘
        (data as NSData).write(toFile: filePath, atomically: true)
        
        print("存入沙盒的路径 \(filePath)")
    }
}


















